package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.ruoyi.system.domain.JobPlanBillApproval;
import com.ruoyi.system.domain.JobPlanBillDeclare;
import com.ruoyi.system.entity.SysActing;
import com.ruoyi.system.mapper.JobPlanBillApprovalMapper;
import com.ruoyi.system.mapper.JobPlanBillDeclareMapper;
import com.ruoyi.system.service.JobPlanBillApprovalService;
import com.ruoyi.system.service.SysActingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作业计划-审批(JobPlanBillApproval)表服务实现类
 *
 * @author makejava
 * @since 2022-11-23 09:20:09
 */
@Slf4j
@Service("jobPlanBillApprovalService")
public class JobPlanBillApprovalServiceImpl implements JobPlanBillApprovalService {

    @Autowired
    private LockTemplate lockTemplate;
    @Autowired
    private SysActingService sysActingService;
    @Resource
    private JobPlanBillDeclareMapper jobPlanBillDeclareDao;
    @Resource
    private JobPlanBillApprovalMapper jobPlanBillApprovalDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public JobPlanBillApproval queryById(Integer id) {
        return this.jobPlanBillApprovalDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param jobPlanBillApproval 筛选条件
     * @param pageRequest         分页对象
     * @return 查询结果
     */
    @Override
    public Page<JobPlanBillApproval> queryByPage(JobPlanBillApproval jobPlanBillApproval, PageRequest pageRequest) {
        long total = this.jobPlanBillApprovalDao.count(jobPlanBillApproval);
        return new PageImpl<>(this.jobPlanBillApprovalDao.queryAllByLimit(jobPlanBillApproval, pageRequest), pageRequest, total);
    }

    @Override
    public List<JobPlanBillApproval> queryAll(JobPlanBillApproval jobPlanBillApproval) {
        return jobPlanBillApprovalDao.queryAll(jobPlanBillApproval);
    }

    /**
     * 新增数据
     *
     * @param jobPlanBillApproval 实例对象
     * @return 实例对象
     */
    @Override
    public JobPlanBillApproval insert(JobPlanBillApproval jobPlanBillApproval) {
        this.jobPlanBillApprovalDao.insert(jobPlanBillApproval);
        return jobPlanBillApproval;
    }

    /**
     * 修改数据
     *
     * @param jobPlanBillApproval 实例对象
     * @return 实例对象
     */
    @Override
    public JobPlanBillApproval update(JobPlanBillApproval jobPlanBillApproval) {
        this.jobPlanBillApprovalDao.update(jobPlanBillApproval);
        return this.queryById(jobPlanBillApproval.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.jobPlanBillApprovalDao.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submit(JobPlanBillApproval jobPlanBillApproval) {
        //1.组装锁的键
        final String key = "JOB_BILL_SUBMIT_" + jobPlanBillApproval.getBillCard();
        log.info("审批_分布式锁key_{}", key);

        //2.完成加锁
        final LockInfo lockInfo = lockTemplate.lock(key, 3600L, 5000L);
        if (null == lockInfo) {
            return false;
        }
        JobPlanBillDeclare jobPlanBillDeclare;
        //3.加锁成功
        try {
            jobPlanBillDeclare = new JobPlanBillDeclare();
            jobPlanBillDeclare.setBillNumber(jobPlanBillApproval.getBillCard());
            List<JobPlanBillDeclare> jobPlanBillDeclares = jobPlanBillDeclareDao.queryAll(jobPlanBillDeclare);
            if (CollectionUtils.isEmpty(jobPlanBillDeclares)) {
                log.error("未找到对应票据:{}", key);
                return false;
            }

            JobPlanBillDeclare planBillDeclare = jobPlanBillDeclares.stream().findFirst().orElse(null);
            if (null == planBillDeclare) {
                return false;
            }

            jobPlanBillDeclare = new JobPlanBillDeclare();
            jobPlanBillDeclare.setId(planBillDeclare.getId());
            jobPlanBillDeclare.setStatus(jobPlanBillApproval.getStatus());
            log.info("审批 更新状态:{}", JSON.toJSON(jobPlanBillDeclare));

            int update = jobPlanBillDeclareDao.update(jobPlanBillDeclare);
            if (update > 0) {
                SysActing sysActing = new SysActing();
                //标题名称
                sysActing.setTitleName("作业票");
                //标题类型
                sysActing.setTitleType("作业票审批");
                //标题详情 (票据号)
                //sysActing.setTitleInfo(jobPlanBillDeclare.getBillNumber());
                //发起人ID (申请人ID)
                //sysActing.setOriginatorId(Integer.valueOf(jobPlanBillDeclare.getApplyPeopleId()));
                //发起人名称 (申请人名称)
                //sysActing.setOriginatorName(jobPlanBillDeclare.getApplyPeople());
                //执行人id (现场批准人ID)
                //sysActing.setExecutorId(Integer.valueOf(jobPlanBillDeclare.getApprovedById()));
                //执行人名称 (现场批准人)
                //sysActing.setExecutorName(jobPlanBillDeclare.getApprovedBy());
                //元数据ID (更优取值,直接新增完票据号返回)
                //int i = null == (jobPlanBillDeclares.stream().findFirst().orElse(null)) ? 0 : jobPlanBillDeclares.stream().findFirst().orElse(null).getId();
                //sysActing.setSourceId(i);

                log.info("申报成功,需要通知待审核人员:{}", JSON.toJSON(sysActing));
                sysActingService.insert(sysActing);

                return true;
            }
        } finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }

        return false;
    }
}
